package com.bookcloud.java21.aitools.aie04;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

/** Today's Sign-in UI Interface 今日签到UI界面 */
public class TodaySignUI extends JPanel {

  private JPanel studentButtonPanel;
  private JLabel totalCountLabel;
  private JLabel signedCountLabel;
  private JLabel unsignedCountLabel;
  private JLabel currentTimeLabel;

  private List<Student> studentData;
  private List<JButton> studentButtons;

  private static final int BUTTONS_PER_ROW = 6;
  private static final Color SIGNED_COLOR = new Color(34, 139, 34);
  private static final Color UNSIGNED_COLOR = new Color(220, 20, 60);
  private static final Color BUTTON_BG_SIGNED = new Color(144, 238, 144);
  private static final Color BUTTON_BG_UNSIGNED = new Color(255, 182, 193);

  public TodaySignUI() {
    initializeComponents();
    loadData();
    setupLayout();
    updateStatistics();
    startTimeUpdater();
  }

  /** Initialize UI components 初始化UI组件 */
  private void initializeComponents() {
    setLayout(new BorderLayout());
    setBackground(Color.WHITE);

    // Initialize data
    studentData = DataUtil.getTodaySignData();
    studentButtons = new ArrayList<>();

    // Create student button panel with grid layout
    studentButtonPanel = new JPanel();
    updateButtonPanel();

    // Statistics labels
    totalCountLabel = new JLabel("总人数: 0");
    signedCountLabel = new JLabel("已签到: 0");
    unsignedCountLabel = new JLabel("未签到: 0");
    currentTimeLabel = new JLabel("当前时间: ");

    // Style the labels
    Font labelFont = new Font("微软雅黑", Font.BOLD, 14);
    totalCountLabel.setFont(labelFont);
    signedCountLabel.setFont(labelFont);
    signedCountLabel.setForeground(SIGNED_COLOR);
    unsignedCountLabel.setFont(labelFont);
    unsignedCountLabel.setForeground(UNSIGNED_COLOR);
    currentTimeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
  }

  /** Setup the layout 设置布局 */
  private void setupLayout() {
    // Top panel with title and statistics
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.setBackground(Color.WHITE);
    topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

    // Title
    JLabel titleLabel = new JLabel("今日签到管理", JLabel.CENTER);
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
    titleLabel.setForeground(new Color(51, 51, 51));

    // Statistics panel
    JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 5));
    statsPanel.setBackground(Color.WHITE);
    statsPanel.add(totalCountLabel);
    statsPanel.add(signedCountLabel);
    statsPanel.add(unsignedCountLabel);

    // Time panel
    JPanel timePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    timePanel.setBackground(Color.WHITE);
    timePanel.add(currentTimeLabel);

    // Combine stats and time
    JPanel infoPanel = new JPanel(new BorderLayout());
    infoPanel.setBackground(Color.WHITE);
    infoPanel.add(statsPanel, BorderLayout.WEST);
    infoPanel.add(timePanel, BorderLayout.EAST);

    topPanel.add(titleLabel, BorderLayout.NORTH);
    topPanel.add(infoPanel, BorderLayout.SOUTH);

    // Main content panel with scroll
    JScrollPane scrollPane = new JScrollPane(studentButtonPanel);
    scrollPane.setBorder(BorderFactory.createTitledBorder("学生签到状态"));
    scrollPane.getViewport().setBackground(Color.WHITE);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    // Bottom panel with refresh button
    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    bottomPanel.setBackground(Color.WHITE);
    bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    JButton refreshButton = new JButton("刷新数据");
    refreshButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    refreshButton.setPreferredSize(new Dimension(100, 30));
    refreshButton.addActionListener(e -> refreshData());

    JButton exportButton = new JButton("导出签到");
    exportButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    exportButton.setPreferredSize(new Dimension(100, 30));
    exportButton.addActionListener(e -> exportSignInData());

    bottomPanel.add(refreshButton);
    bottomPanel.add(exportButton);

    // Add components to main panel
    add(topPanel, BorderLayout.NORTH);
    add(scrollPane, BorderLayout.CENTER);
    add(bottomPanel, BorderLayout.SOUTH);
  }

  /** Update button panel with student buttons 更新按钮面板 */
  private void updateButtonPanel() {
    studentButtonPanel.removeAll();
    studentButtons.clear();

    // Calculate rows needed
    int rows = (int) Math.ceil((double) studentData.size() / BUTTONS_PER_ROW);
    studentButtonPanel.setLayout(new GridLayout(rows, BUTTONS_PER_ROW, 10, 10));
    studentButtonPanel.setBackground(Color.WHITE);
    studentButtonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    // Create buttons for each student
    for (int i = 0; i < studentData.size(); i++) {
      Student student = studentData.get(i);
      JButton studentButton = createStudentButton(student, i);
      studentButtons.add(studentButton);
      studentButtonPanel.add(studentButton);
    }

    // Fill remaining slots with empty panels if needed
    int totalSlots = rows * BUTTONS_PER_ROW;
    for (int i = studentData.size(); i < totalSlots; i++) {
      JPanel emptyPanel = new JPanel();
      emptyPanel.setBackground(Color.WHITE);
      studentButtonPanel.add(emptyPanel);
    }

    studentButtonPanel.revalidate();
    studentButtonPanel.repaint();
  }

  /** Create a button for a student 为学生创建按钮 */
  private JButton createStudentButton(Student student, int index) {
    JButton button = new JButton();

    // Set button text with student info,增加签到状态
    String buttonText =
        String.format(
            "<html><center><b>%s</b><br><small>%s</small><br><font color='%s'>%s</font></center></html>",
            student.getName(),
            student.getStuNo(),
            student.getStatus() == 1 ? "green" : "red",
            student.getStatusText());
    button.setText(buttonText);

    // Set button appearance based on sign-in status
    updateButtonAppearance(button, student);

    // Set button properties
    button.setPreferredSize(new Dimension(120, 80));
    button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    button.setFocusPainted(false);
    button.setBorder(BorderFactory.createRaisedBevelBorder());

    // Add click event
    button.addActionListener(new StudentButtonListener(student, button, index));

    return button;
  }

  /** Update button appearance based on student status 根据学生状态更新按钮外观 */
  private void updateButtonAppearance(JButton button, Student student) {
    if (student.getStatus() == 1) {
      // Already signed in
      button.setBackground(BUTTON_BG_SIGNED);
      button.setForeground(SIGNED_COLOR);
      button.setEnabled(true);
    } else {
      // Not signed in yet
      button.setBackground(BUTTON_BG_UNSIGNED);
      button.setForeground(UNSIGNED_COLOR);
      button.setEnabled(true);
    }
  }

  /** Load student data 加载学生数据 */
  private void loadData() {
    updateButtonPanel();
  }

  /** Student button click listener 学生按钮点击监听器 */
  private class StudentButtonListener implements ActionListener {
    private Student student;
    private JButton button;
    private int index;

    public StudentButtonListener(Student student, JButton button, int index) {
      this.student = student;
      this.button = button;
      this.index = index;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
      if (student.getStatus() == 0) {
        // Sign in the student
        student.setStatus(1);
        // student.setSignDate(java.time.LocalDate.now());
        // 获取签到时间
        String signTime = java.time.LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        student.setSignTime(signTime);
        // Update button appearance
        updateButtonAppearance(button, student);

        // Update button text to show sign-in time
        String newButtonText =
            String.format(
                "<html><center><b>%s</b><br><small>%s</small><br><font color='green'>已签到</font></center></html>",
                student.getName(), student.getStuNo());
        button.setText(newButtonText);

        // Update statistics
        updateStatistics();

        // Show confirmation with formatted time
        String currentTime =
            java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日 HH:mm:ss"));
        JOptionPane.showMessageDialog(
            TodaySignUI.this,
            student.getName() + " 已签到！\n" + currentTime,
            "签到提示",
            JOptionPane.INFORMATION_MESSAGE);
      } else {
        // Already signed in, show info with formatted time
        String signTime =
            java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日 HH:mm:ss"));
        JOptionPane.showMessageDialog(
            TodaySignUI.this,
            student.getName() + " 已经签到！\n" + signTime,
            "签到提示",
            JOptionPane.INFORMATION_MESSAGE);
      }
    }
  }

  /** Update statistics 更新统计信息 */
  private void updateStatistics() {
    int total = studentData.size();
    int signed = (int) studentData.stream().filter(s -> s.getStatus() == 1).count();
    int unsigned = total - signed;

    totalCountLabel.setText("总人数: " + total);
    signedCountLabel.setText("已签到: " + signed);
    unsignedCountLabel.setText("未签到: " + unsigned);
  }

  /** Refresh data 刷新数据 */
  private void refreshData() {
    studentData = DataUtil.getTodaySignData();
    updateButtonPanel();
    updateStatistics();
    JOptionPane.showMessageDialog(this, "数据已刷新！", "提示", JOptionPane.INFORMATION_MESSAGE);
  }

  /** Export sign-in data 导出签到数据 */
  private void exportSignInData() {
    StringBuilder sb = new StringBuilder();
    sb.append("签到统计报告\n");
    sb.append("===================\n");
    sb.append("统计日期：").append(java.time.LocalDate.now()).append("\n");
    sb.append("总人数：").append(studentData.size()).append("\n");

    int signed = (int) studentData.stream().filter(s -> s.getStatus() == 1).count();
    sb.append("已签到：").append(signed).append("\n");
    sb.append("未签到：").append(studentData.size() - signed).append("\n\n");

    sb.append("已签到学生名单：\n");
    studentData.stream()
        .filter(s -> s.getStatus() == 1)
        .forEach(s -> sb.append(s.getName()).append(" (").append(s.getStuNo()).append(")\n"));

    sb.append("\n未签到学生名单：\n");
    studentData.stream()
        .filter(s -> s.getStatus() == 0)
        .forEach(s -> sb.append(s.getName()).append(" (").append(s.getStuNo()).append(")\n"));

    JTextArea textArea = new JTextArea(20, 50);
    textArea.setText(sb.toString());
    textArea.setEditable(false);
    textArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));

    JScrollPane scrollPane = new JScrollPane(textArea);
    JOptionPane.showMessageDialog(this, scrollPane, "签到数据导出", JOptionPane.INFORMATION_MESSAGE);
  }

  /** Start time updater 启动时间更新器 */
  private void startTimeUpdater() {
    Timer timer =
        new Timer(
            1000,
            e -> {
              currentTimeLabel.setText(
                  "当前时间: "
                      + java.time.LocalDateTime.now()
                          .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            });
    timer.start();
  }
}
